﻿using DevExpress.ExpressApp.Blazor.Components.Models;
using Microsoft.AspNetCore.Components;

namespace EasyXaf.DynamicForm.Blazor;

public class DynamicFormEditorModel : DxComponentModelBase, IHandleValueComponentModel
{
    public string Value
    {
        get => GetPropertyValue<string>();
        set => SetPropertyValue(value);
    }

    public EventCallback<string> ValueChanged
    {
        get => GetPropertyValue<EventCallback<string>>();
        set => SetPropertyValue(value);
    }

    public string Schema
    {
        get => GetPropertyValue<string>();
        set => SetPropertyValue(value);
    }

    public override Type ComponentType => typeof(DynamicFormEditorRenderer);

    private event EventHandler<HandleValueEventArgs> _valueChanged;

    event EventHandler<HandleValueEventArgs> IHandleValueComponentModel.ValueChanged
    {
        add => _valueChanged += value;
        remove => _valueChanged -= value;
    }

    object IHandleValueComponentModel.Value
    {
        get => Value;
        set => Value = value as string;
    }

    public DynamicFormEditorModel()
    {
        ValueChanged = EventCallback.Factory.Create<string>(this, text =>
        {
            _valueChanged?.Invoke(this, new HandleValueEventArgs(text));
        });
    }
}
